import matplotlib
import matplotlib.pyplot as plt
import numpy as np

def combination_rotation_animation(x, y, z, begin, amoung, step):
    from matplotlib.animation import PillowWriter, FFMpegWriter

    metadata = dict(title="Movie")
    writer1 = PillowWriter(fps=15, metadata=metadata)
    writer2 = FFMpegWriter(fps=15, metadata=metadata)
    for j in writer1, writer2:
        if j == writer1:
            text = ".gif"
        else:
            text = ".mp4"

        fig = plt.figure(figsize=(12, 12), dpi=100)
        ax = fig.add_subplot(projection='3d')

        interval = 360 / amoung
        count = 0
        start = 0
        total = 360

        with j.saving(fig, "B_animate"+text, 100):
            for i in tqdm.tqdm(np.linspace(-180, 180, total)):
                ax.clear()

                count += 360 / total
                if count > interval:
                    count = 0
                    start += step

                x1, kx = find_max_min(x[start: start + step])
                y1, ky = find_max_min(y[start: start + step])
                z1, kz = find_max_min(z[start: start + step])
                x2, y2, z2 = elipse(kx, ky, kz)

                ax.plot_wireframe(x2, y2, z2, linewidth=0.1, color='b')
                ax.scatter(x1, y1, z1, c='black',
                           marker=">")
                ax.view_init(azim=i, elev=28)
                date_begin = date(2023, 1, 1) + timedelta(days=df_B.iloc[begin+start]["Day"])
                plt.title(
                    "Day: " + str(date_begin) + " Hour: " + str(df_B.iloc[begin+start]["Hour"]) + " - " + str(
                        df_B.iloc[begin + start + step]["Hour"]) + " Point: " + str(begin+start) + " - " + str(begin + start + step), size=20)
                plt.xlabel('$Bx$', size=20, color='g')
                plt.ylabel('$By$', size=20, color='g')
                ax.set_zlabel('$Bz$', size=20)
                j.grab_frame()

def velocity_rotation(x, y, z, begin, amoung, step):
    from matplotlib.animation import PillowWriter, FFMpegWriter

    metadata = dict(title="Movie")
    writer1 = PillowWriter(fps=15, metadata=metadata)
    writer2 = FFMpegWriter(fps=15, metadata=metadata)
    for j in writer1, writer2:
        if j == writer1:
            text = ".gif"
        else:
            text = ".mp4"

        fig = plt.figure(figsize=(12, 12), dpi=100)
        ax = fig.add_subplot(projection='3d')

        interval = 360 / amoung
        count = 0
        start = 0
        total = 360

        with j.saving(fig, "V_animate" + text, 100):
            for i in tqdm.tqdm(np.linspace(-180, 180, total)):
                ax.clear()

                count += 360 / total
                if count > interval:
                    count = 0
                    start += step
                ax.scatter(x[start: start + step], y[start: start + step], z[start: start + step], c='black',
                           marker=">")
                ax.view_init(azim=i, elev=28)
                date_begin = date(2023, 1, 1) + timedelta(days=df_V.iloc[begin + start]["Day"]-1)
                plt.title("Day: " + str(date_begin), size=20)
                plt.xlabel('$Vx$', color='g', size=20)
                plt.ylabel('$Vy$', color='g', size=20)
                ax.set_zlabel('$Vz$', size=20)
                j.grab_frame()

def animation_rotate(x, y, z):
    from matplotlib.animation import PillowWriter

    metadata = dict(title="Movie")
    writer = PillowWriter(fps=15, metadata=metadata)
    fig = plt.figure(figsize=(12, 12), dpi=100)
    ax = fig.add_subplot(projection='3d')

    with writer.saving(fig, "V_animate.gif", 100):
        for i in np.linspace(-180, 180, 1440):
            ax.clear()
            ax.scatter(x, y, z, c='black', marker=">")
            ax.view_init(azim=i, elev=28)
            plt.xlabel('$Vx$', color='g')
            plt.ylabel('$Vy$', color='g')
            ax.set_zlabel('$Vz$')
            writer.grab_frame()


def Anime(x, y, z, len_step):
    from matplotlib.animation import PillowWriter

    metadata = dict(title="Movie")
    writer = PillowWriter(fps=15, metadata=metadata)

    fig = plt.figure(figsize=(12, 12), dpi=100)
    ax = fig.add_subplot(projection='3d')

    def update(i):
        ax.clear()
        ax.scatter(x[i * len_step:i * len_step + len_step], y[i * len_step:i * len_step + len_step],
                   z[i * len_step:i * len_step + len_step], s=0.5)
        plt.title(str(i * len_step))
        plt.xlabel('$Bx$', color='g')
        plt.ylabel('$By$', color='g')
        ax.set_zlabel('$Bz$')

    ani = animation.FuncAnimation(fig, update, np.arange(100), interval=1000, repeat=False)

    with writer.saving(fig, "Banimate-fix.gif", 100):
        for i in range(100):
            ax.clear()
            ax.scatter(x[i * len_step:i * len_step + len_step], y[i * len_step:i * len_step + len_step],
                       z[i * len_step:i * len_step + len_step])
            plt.title(str(i * len_step))
            plt.xlabel('$Bx$', color='g')
            plt.ylabel('$By$', color='g')
            ax.set_zlabel('$Bz$')
            writer.grab_frame()
    plt.show()


def Video(x, y, z, len_step):
    from matplotlib.animation import FFMpegWriter

    metadata = dict(title="Movie")
    writer2 = FFMpegWriter(fps=2, metadata=metadata)

    fig = plt.figure(figsize=(12, 12), dpi=100)
    ax = fig.add_subplot(projection='3d')

    with writer2.saving(fig, "Banimate.mp4", 100):
        for i in range(100):
            ax.clear()
            ax.scatter(x[i * len_step:i * len_step + len_step], y[i * len_step:i * len_step + len_step],
                       z[i * len_step:i * len_step + len_step])
            plt.title(str(i * len_step))
            plt.xlabel('$Bx$', color='g')
            plt.ylabel('$By$', color='g')
            ax.set_zlabel('$Bz$')
            # ax.set_xlim(min(X), max(X))
            # ax.set_ylim(min(Y), max(Y))
            # ax.set_zlim(min(Z), max(Z))
            writer2.grab_frame()
    plt.show()

    fig = plt.figure(figsize=plt.figaspect(0.5))
    amoung = 3
    j = 1
    for i in range(24, 33):
        ax = fig.add_subplot(amoung, amoung, j, projection='3d')
        ax.scatter(x[i * len_step:i * len_step + len_step], y[i * len_step:i * len_step + len_step],
                   z[i * len_step:i * len_step + len_step], s=0.01)
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.set_zticklabels([])
        j += 1
    plt.show()

